package uk.ac.cam.echo.app;

import java.io.IOException;
import uk.ac.cam.echo.messages.LocationMessage;
import uk.ac.cam.echo.messages.Message;
import uk.ac.cam.echo.messages.UserMessage;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author Matt Thomson, Tom Smith, Vladimir Kovalev
 */

public class ScannerActivity extends SecondaryActivity
{
	private String recentRFID = null;
	private Scanner scanner;
	private TextView main;
	private Button add;
	private Button cancel;
	private Button home;
	private View uploadingAnimation;

	private final Object scannerLock = new Object();
	private boolean isProcessingTag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.scanner);

		scanner = new Scanner(this);

		main = (TextView) findViewById(R.id.mainText);
		add = (Button) findViewById(R.id.addFriend);
		cancel = (Button) findViewById(R.id.cancelAddFriend);
		home = (Button) findViewById(R.id.scannerHome);
		uploadingAnimation = findViewById(R.id.scannerLoadingAnimation);

		add.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (recentRFID == null)
				{
					showMessage("No tags selected.", true);
				}
				else
				{
					Thread t = new Thread()
					{
						@Override
						public void run()
						{
							try
							{
								disableButton(add);
								showView(uploadingAnimation);

								// Add Friend
								DBInt.getInstance().addFriend(recentRFID);

								// Open FriendsActivity huh?
								Intent i = new Intent(self, FriendsActivity.class);
								i.putExtra("option", "friends");
								i.putExtra("title", "Friend List");
								self.startActivity(i);
								self.finish();
							}
							catch (IOException e)
							{
								showMessage("Failed to connect to the database.", false);
								cancel.performClick();
							}
							finally
							{
								hideView(uploadingAnimation);
							}
						}
					};
				
					t.run();
				}
			}
		});

		cancel.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				self.runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						recentRFID = null;
						disableButton(add);
						disableButton(cancel);
						uploadingAnimation.setVisibility(View.VISIBLE);
						main.setText("");
					}
				});
			}
		});

		home.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				goHome();
			}
		});
	}

	@Override
	public void onPause()
	{
		super.onPause();
		scanner.pause();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (!scanner.isActive)
			scanner.startSniffing();
		else
			scanner.resume();
	}

	@Override
	public void onNewIntent(Intent intent)
	{
		super.onNewIntent(intent);

		synchronized (scannerLock)
		{
			final String rfid = Scanner.decode(intent);

			if (rfid != null && !isProcessingTag)
			{
				isProcessingTag = true;
				recentRFID = rfid;
				Thread t = new Thread()
				{
					@Override
					public void run()
					{
						try
						{
							showView(uploadingAnimation);

							// get user data from database
							Message m = DBInt.getInstance().scanRFID(rfid);

							if (m instanceof UserMessage)
							{
								final UserMessage u = (UserMessage) m;

								// Check if the person is your friend
								final boolean isFriend = DBInt.getInstance().getFriendList().contains(rfid);

								enableButton(cancel);
								
								if (isFriend)
									disableButton(add);
								else
									enableButton(add);
								
								
								self.runOnUiThread(new Runnable()
								{
									@Override
									public void run()
									{
										uploadingAnimation.setVisibility(View.GONE);
										main.setText(u.getForename() + " " + u.getSurname());
									}
								});
							}
							else if (m instanceof LocationMessage)
							{
								Intent intent = new Intent(self, MapActivity.class);
								self.startActivity(intent);
								self.finish();
							}
							else
							{
								throw new Exception("Unknown message type received from the database");
							}
						}
						catch (Exception e)
						{
							showOKMessage("Unable to connect to the Database.");
						}
						finally
						{
							synchronized (scannerLock)
							{
								isProcessingTag = false;
							}
						}
					}
				};
				t.start();
			}
		}
	}
}